<template>
  <div>
    <DynamicTable header-title="分类字典管理" show-index :data-request="loadTableData" :columns="columns">
      <template #toolbar>
        <a-button type="primary" @click="openCategaryModal({})">
          新增
        </a-button>
      </template>
    </DynamicTable>
  </div>
</template>

<script lang="tsx" setup>
  import { ref } from 'vue';
  import { cloneDeep } from 'lodash-es';
  import { baseColumns, type TableListItem, type TableColumnItem } from './columns';
  import { categarySchemas } from './formSchemas';
  import type { TreeSelectProps } from 'ant-design-vue';
  import { getCategaryList, updateCategary, createCategary, deleteCategary } from '@/api/workorder/categary';
  import { useTable } from '@/components/core/dynamic-table';
  import { useFormModal } from '@/hooks/useModal/useFormModal';
  import { formatCategary2Tree } from '@/core/permission/utils';

  defineOptions({
    name: 'SysCategary',
  });

  const categaryTree = ref<TreeSelectProps['treeData']>([]);
  const [DynamicTable, dynamicTableInstance] = useTable({
    search: false,
    pagination: false,
    size: 'small',
    rowKey: 'id',
    bordered: true,
    scroll: { x: 2000 },
  });
  const [showModal] = useFormModal();

  const loadTableData = async () => {
    let data = await getCategaryList();
    categaryTree.value = formatCategary2Tree(
      cloneDeep(data),
      "0",
    );
    return { list: formatCategary2Tree(cloneDeep(data), "0") };
  };

  const openCategaryModal = async (record: Partial<TableListItem>) => {
    const [formRef] = await showModal({
      modalProps: {
        title: `${record.id ? '编辑' : '新增'}分类字典`,
        width: 700,
        onFinish: async (values) => {
          console.log('新增/编辑分类字典', values);
          record.id && (values.id = record.id);
          values.perms = values.perms?.join(',');
          await (record.id ? updateCategary : createCategary)(values);
          dynamicTableInstance.reload();
        },
      },
      formProps: {
        labelWidth: 100,
        schemas: categarySchemas,
      },
    });

    formRef?.updateSchema([
      {
        field: 'parentId',
        componentProps: {
          treeDefaultExpandedKeys: ['0'].concat(record?.keyPath || []),
          treeData: ref([{ id: '0', name: '一级分类字典', children: categaryTree.value }]),
        },
      },
    ]);

    formRef?.setFieldsValue({
      ...record,
      parentId: record.parentId ?? '0',
    });
  };
  const delRowConfirm = async (record: TableListItem) => {
    await deleteCategary({ id: record.id });
    dynamicTableInstance.reload();
  };

  const columns: TableColumnItem[] = [
    ...baseColumns,
    {
      title: '操作',
      width: 160,
      dataIndex: 'ACTION',
      hideInSearch: true,
      align: 'center',
      fixed: 'right',
      actions: ({ record }) => [
        {
          label: '编辑',
          onClick: () => openCategaryModal(record),
        },
        {
          label: '删除',
          popConfirm: {
            title: '你确定要删除吗？',
            onConfirm: () => delRowConfirm(record),
          },
        },
      ],
    },
  ];
</script>
